package com.masterclient.app.modules.purchase.widget;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.KeyboradUtil;
import com.masterclient.app.R;
import com.sobot.chat.camera.util.DeviceUtil;

public class PurchaseShopCartEditDialog extends Dialog implements View.OnLayoutChangeListener {

    private EditText messageTextView;
    private TextView mSendView;
    private Context mContext;
    private RelativeLayout rlDlg;
    private int mLastDiff = 0;
    private OnTextSendListener mOnTextSendListener;

    private LinearLayout rldlgview;
    private Handler mainHandler;

    private static final int MIN_DELAY_TIME = 800;  // 两次显示间隔不能少于800ms
    private static long lastClickTime;

    private LiveInputLengthWatcher mLiveInputLengthWatcher;
    private int heightDifference;

    public Handler getMainHandler() {
        if (mainHandler == null) {
            mainHandler = new Handler(Looper.getMainLooper());
        }
        return mainHandler;
    }

    public PurchaseShopCartEditDialog(Context context, int theme,String num) {
        super(context, theme);

        mContext = context;
        setContentView(R.layout.dialog_purchase_shop_cart_input);

        mSendView = findViewById(R.id.et_input_send);
        messageTextView = (EditText) findViewById(R.id.et_input_message);
        messageTextView.setText(num);
        mLiveInputLengthWatcher = new LiveInputLengthWatcher(120, messageTextView);
        messageTextView.addTextChangedListener(mLiveInputLengthWatcher);
        mSendView.setOnClickListener(v -> sendToMessage());
        messageTextView.setOnKeyListener((v, keyCode, event) -> {
            // 这两个条件必须同时成立，如果仅仅用了enter判断，就会执行两次
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN || keyCode == EditorInfo.IME_ACTION_SEND) {
                sendToMessage();
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                return true;
            }
            return false;
        });

        rlDlg = findViewById(R.id.rl_outside_view);
        rlDlg.setOnClickListener(v -> {
            if(v.getId() != R.id.rl_inputdlg_view) {
                if (messageTextView != null) {
                    KeyboradUtil.closeKeybord(messageTextView);
                }
                dismiss();
            }
        });

        messageTextView.requestFocus();
        rldlgview = (LinearLayout) findViewById(R.id.rl_inputdlg_view);
        rldlgview.addOnLayoutChangeListener(this);
        getMainHandler().postDelayed(() -> {
            if (heightDifference <= 0) {
                //TODO:刷新layout防止onLayoutChange不即使回调
                if (rldlgview != null) {
                    rldlgview.requestLayout();
                }
            }
        },300);
    }

    private void sendToMessage() {
        if (messageTextView.getText()!=null && messageTextView.getText().toString().length() > 0) {
            if (mOnTextSendListener != null) {
                mOnTextSendListener.onTextSend("" + messageTextView.getText());
            }
            messageTextView.setText("");
            if (messageTextView != null) {
                KeyboradUtil.closeKeybord(messageTextView);
            }
            dismiss();
        } else {
            if (!isFastClick()) {
                ToastUtil.showToast("请输入内容");
            }
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        Rect r = new Rect();
        //获取当前界面可视部分
        getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        //TODO:键盘高度问题1
        //获取屏幕的高度 (不包含statusBar)
        int screenHeight =  getWindow().getDecorView().getRootView().getHeight();

        //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
        heightDifference = screenHeight - r.bottom;
        if (heightDifference  > 100) {
            rldlgview.setVisibility(View.VISIBLE);
            if (mOnTextSendListener != null) {
                int statusBarHeight = DeviceUtil.getStatusBarHeight(mContext);
            }
        }
        if (heightDifference <= 0 && mLastDiff > 0){
            if (messageTextView != null) {
                KeyboradUtil.closeKeybord(messageTextView);
            }
            dismiss();
        }
        mLastDiff = heightDifference;
    }

    public void setmOnTextSendListener(OnTextSendListener onTextSendListener) {
        this.mOnTextSendListener = onTextSendListener;
    }

    /**
    * 关闭键盘
    * */
    public void closeKeyBoard() {
        if (messageTextView != null) {
            KeyboradUtil.closeKeybord(messageTextView);
        }
        dismiss();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        getMainHandler().removeCallbacksAndMessages(null);
        if (rldlgview != null) {
            rldlgview.removeOnLayoutChangeListener(this);
        }
        mOnTextSendListener = null;
        //dismiss之前重置mLastDiff值避免下次无法打开
        mLastDiff = 0;
    }

    @Override
    public void show() {
        super.show();
    }

    private static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }


    public interface OnTextSendListener {
        void onTextSend(String msg);
    }
}
